package view.agenda;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;

import model.entidades.Agendamento;
import model.entidades.Paciente;
import model.entidades.Usuario;
import utils.Constantes;
import utils.Formatacao;
import view.componentes.AgendaTableModel;
import view.consulta.TelaConsulta;
import view.principal.TelaPrincipal;
import controller.ControladorAgendamento;

public class TelaAgendaProfissional extends JPanel implements ActionListener, KeyListener {

	private static final long serialVersionUID = 1L;

	private JPanel panelNorte;
	private JPanel panelCentro;
	private JPanel panelResumoPaciente;

	private JSeparator separator;

	private JLabel lblAgenda;
	private JLabel lblNomeProfissionalLogado;
	private JLabel lblDataAtual;
	private JLabel lblResumoPaciente;
	private JLabel lblNomeCompleto;
	private JLabel lblNomePaciente;
	private JLabel lblDataNascimentoIdade;
	private JLabel lblDataNascimentoIdadePaciente;
	private JLabel lblSexo;
	private JLabel lblSexoPaciente;
	private JLabel lblEscolaridade;
	private JLabel lblEscolaridadePaciente;
	private JLabel lblTipoConvenioAgendamento;
	private JLabel lblConvenioPaciente;
	private JLabel lblObservacoes;

	private JScrollPane scrollPaneAgenda;
	private JTable tableAgenda;
	private AgendaTableModel agendaTableModel;

	private JScrollPane scrollPaneObservacoesAgendamento;
	private JTextArea txtObservacoesAgendamento;

	private JButton btnRealizarAtendimento;

	private Calendar dataAtual;

	private Usuario profissionalLogado;

	private Agendamento agendamento;

	private Paciente paciente;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}else{
							UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
						}
					}
					JFrame frame = new JFrame();
					frame.setBounds(100, 100, 950, 700);
					frame.setLocationRelativeTo(null);
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					frame.getContentPane().setLayout(new BorderLayout(0, 0));
					frame.getContentPane().add(new TelaAgendaProfissional(), BorderLayout.CENTER);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the panel.
	 */
	public TelaAgendaProfissional() {
		this.profissionalLogado = TelaPrincipal.getUsuarioLogado();
		dataAtual = Calendar.getInstance();
		this.agendamento = null;
		inicicializaComponentes();
		atualizaTabela();
	}

	private void inicicializaComponentes() {
		setBackground(Color.WHITE);
		setLayout(new BorderLayout(0, 0));

		panelCentro = new JPanel();
		panelCentro.setBackground(Color.WHITE);
		add(panelCentro, BorderLayout.CENTER);

		lblAgenda = new JLabel("Lista de Atendimentos do Dia");
		lblAgenda.setFont(new Font("SansSerif", Font.BOLD, 18));

		panelResumoPaciente = new JPanel();
		panelResumoPaciente.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelResumoPaciente.setBackground(Color.WHITE);

		scrollPaneAgenda = new JScrollPane();

		lblNomeProfissionalLogado = new JLabel();
		lblNomeProfissionalLogado.setFont(new Font("SansSerif", Font.BOLD, 18));

		lblDataAtual = new JLabel();
		lblDataAtual.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDataAtual.setFont(new Font("SansSerif", Font.BOLD, 18));

		btnRealizarAtendimento = new JButton("Realizar Atendimento");
		btnRealizarAtendimento.setActionCommand("REALIZAR");
		btnRealizarAtendimento.setIcon(new ImageIcon(TelaAgendaProfissional.class.getResource("/resources/images/ic_assignment_turned_in_white_48dp.png")));
		btnRealizarAtendimento.setForeground(Color.WHITE);
		btnRealizarAtendimento.setBackground(new Color(0, 102, 153));
		btnRealizarAtendimento.setFont(new Font("SansSerif", Font.BOLD, 14));
		btnRealizarAtendimento.setEnabled(false);
		GroupLayout gl_panelCentro = new GroupLayout(panelCentro);
		gl_panelCentro.setHorizontalGroup(
				gl_panelCentro.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelCentro.createSequentialGroup()
						.addGap(12)
						.addGroup(gl_panelCentro.createParallelGroup(Alignment.TRAILING)
								.addGroup(gl_panelCentro.createSequentialGroup()
										.addComponent(lblNomeProfissionalLogado, GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(lblDataAtual, GroupLayout.PREFERRED_SIZE, 376, GroupLayout.PREFERRED_SIZE))
										.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(scrollPaneAgenda, GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
												.addPreferredGap(ComponentPlacement.UNRELATED)
												.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING, false)
														.addComponent(btnRealizarAtendimento, GroupLayout.PREFERRED_SIZE, 315, GroupLayout.PREFERRED_SIZE)
														.addComponent(panelResumoPaciente, GroupLayout.PREFERRED_SIZE, 315, GroupLayout.PREFERRED_SIZE))))
														.addGap(12))
				);
		gl_panelCentro.setVerticalGroup(
				gl_panelCentro.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panelCentro.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblNomeProfissionalLogado, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblDataAtual, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(panelResumoPaciente, GroupLayout.DEFAULT_SIZE, 491, Short.MAX_VALUE)
												.addPreferredGap(ComponentPlacement.UNRELATED)
												.addComponent(btnRealizarAtendimento))
												.addComponent(scrollPaneAgenda, GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE))
												.addGap(15))
				);
		gl_panelCentro.linkSize(SwingConstants.VERTICAL, new Component[] {lblNomeProfissionalLogado, lblDataAtual});

		tableAgenda = new JTable();
		tableAgenda.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPaneAgenda.setViewportView(tableAgenda);

		lblResumoPaciente = new JLabel("Resumo do Paciente");
		lblResumoPaciente.setFont(new Font("SansSerif", Font.BOLD, 16));
		lblResumoPaciente.setHorizontalAlignment(SwingConstants.CENTER);

		lblNomeCompleto = new JLabel("Nome Completo:");

		lblNomePaciente = new JLabel();
		lblNomePaciente.setFont(new Font("SansSerif", Font.BOLD, 12));

		lblDataNascimentoIdade = new JLabel("Data de Nascimento - Idade:");

		lblDataNascimentoIdadePaciente = new JLabel();
		lblDataNascimentoIdadePaciente.setFont(new Font("SansSerif", Font.BOLD, 12));

		separator = new JSeparator();

		lblSexo = new JLabel("Sexo:");

		lblSexoPaciente = new JLabel();
		lblSexoPaciente.setFont(new Font("SansSerif", Font.BOLD, 12));

		lblEscolaridade = new JLabel("Escolaridade:");

		lblEscolaridadePaciente = new JLabel();
		lblEscolaridadePaciente.setFont(new Font("SansSerif", Font.BOLD, 12));

		lblTipoConvenioAgendamento = new JLabel("Conv\u00EAnio:");

		lblConvenioPaciente = new JLabel();
		lblConvenioPaciente.setFont(new Font("SansSerif", Font.BOLD, 12));

		lblObservacoes = new JLabel("Observa\u00E7\u00F5es:");

		scrollPaneObservacoesAgendamento = new JScrollPane();
		scrollPaneObservacoesAgendamento.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		txtObservacoesAgendamento = new JTextArea();
		txtObservacoesAgendamento.setWrapStyleWord(true);
		txtObservacoesAgendamento.setLineWrap(true);
		txtObservacoesAgendamento.setEditable(false);
		scrollPaneObservacoesAgendamento.setViewportView(txtObservacoesAgendamento);
		GroupLayout gl_panelResumoPaciente = new GroupLayout(panelResumoPaciente);
		gl_panelResumoPaciente.setHorizontalGroup(
				gl_panelResumoPaciente.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelResumoPaciente.createSequentialGroup()
						.addGroup(gl_panelResumoPaciente.createParallelGroup(Alignment.TRAILING)
								.addComponent(lblTipoConvenioAgendamento, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblConvenioPaciente, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblEscolaridadePaciente, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblEscolaridade, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblSexoPaciente, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblSexo, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblNomeCompleto, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(separator, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblNomePaciente, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblDataNascimentoIdade, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblDataNascimentoIdadePaciente, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
								.addComponent(lblResumoPaciente, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE))
								.addGap(1))
								.addComponent(scrollPaneObservacoesAgendamento, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
								.addComponent(lblObservacoes, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
				);
		gl_panelResumoPaciente.setVerticalGroup(
				gl_panelResumoPaciente.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelResumoPaciente.createSequentialGroup()
						.addGap(10)
						.addComponent(lblResumoPaciente)
						.addGap(18)
						.addComponent(separator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(lblNomeCompleto)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblNomePaciente)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(lblDataNascimentoIdade)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblDataNascimentoIdadePaciente)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(lblSexo)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblSexoPaciente)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(lblEscolaridade)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblEscolaridadePaciente)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(lblTipoConvenioAgendamento)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblConvenioPaciente)
						.addPreferredGap(ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
						.addComponent(lblObservacoes)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(scrollPaneObservacoesAgendamento, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
						.addContainerGap())
				);
		panelResumoPaciente.setLayout(gl_panelResumoPaciente);

		panelCentro.setLayout(gl_panelCentro);

		panelNorte = new JPanel();
		add(panelNorte, BorderLayout.NORTH);

		panelNorte.add(lblAgenda);

		atualizaLabels();

		preencheTabela();

		tableAgenda.addMouseListener(new MouseAdapter() {  
			public void mouseClicked(MouseEvent e) {  
				cliqueTabela(e);
			}  
		});
		
		tableAgenda.addKeyListener(this);

		btnRealizarAtendimento.addActionListener(this);
	}

	private void atualizaLabels() {
		lblNomeProfissionalLogado.setText(profissionalLogado.getNome());
		lblDataAtual.setText(new SimpleDateFormat("EEEE, dd 'de' MMMMMMMMM 'de' yyyy").format(dataAtual.getTime()));
		lblNomePaciente.setText("");
		lblDataNascimentoIdadePaciente.setText("");
		lblSexoPaciente.setText("");
		lblEscolaridadePaciente.setText("");
		lblConvenioPaciente.setText("");
	}

	private void preencheTabela() {
		ControladorAgendamento controladorAgendamento = new ControladorAgendamento();
		List<Agendamento> lista = controladorAgendamento.buscaPorParametros(profissionalLogado, dataAtual);
		agendaTableModel = new AgendaTableModel(lista, profissionalLogado, Constantes.COLUNAS_AGENDA_PROFISSIONAL);
		tableAgenda.setModel(agendaTableModel);
		tableAgenda.getColumnModel().getColumn(0).setPreferredWidth(60);
		tableAgenda.getColumnModel().getColumn(0).setMaxWidth(60);
		tableAgenda.getColumnModel().getColumn(2).setPreferredWidth(120);
		tableAgenda.getColumnModel().getColumn(2).setMaxWidth(120);
		tableAgenda.getColumnModel().getColumn(3).setPreferredWidth(80);
		tableAgenda.getColumnModel().getColumn(3).setMaxWidth(80);
	}

	private void atualizaTabela() {
		Timer timer = new Timer();  
		TimerTask task = new TimerTask() {  
			public void run() {
				
				SwingUtilities.invokeLater(new Runnable() {
					
					@Override
					public void run() {
						preencheTabela(); 
					}
				});
				 
			}  
		};  
		timer.schedule(task, 60000, 60000);
	}

	private void cliqueTabela(MouseEvent e) {

		if (e.getClickCount() == 1) {  
			Point p = e.getPoint();  
			int row = tableAgenda.rowAtPoint(p);
			acaoListenersAgenda(row);
		} 

	}

	private void acaoListenersAgenda(int row) {
		
		if(row >= 0){
			agendamento = agendaTableModel.getItemLinha(row);
			if (agendamento == null) {
				paciente = null;
				lblNomePaciente.setText("");
				lblDataNascimentoIdadePaciente.setText("");
				lblSexoPaciente.setText("");
				lblEscolaridadePaciente.setText("");
				lblConvenioPaciente.setText("");
				txtObservacoesAgendamento.setText("");
				btnRealizarAtendimento.setEnabled(false);
			} else {
				paciente = agendamento.getPaciente();
				lblNomePaciente.setText(paciente.getNome());
				lblDataNascimentoIdadePaciente.setText(Formatacao.dataNascimentoIdade(paciente.getDataNascimento()));
				lblSexoPaciente.setText(paciente.getSexo());
				lblEscolaridadePaciente.setText(paciente.getEscolaridade());
				lblConvenioPaciente.setText(agendamento.getConvenio().getNomeExibicao());
				txtObservacoesAgendamento.setText(agendamento.getObservacoes());
				if (agendamento.getStatus().equalsIgnoreCase(Constantes.STATUS_ATENDIDO)) {
					btnRealizarAtendimento.setEnabled(false);
				} else {
					btnRealizarAtendimento.setEnabled(true);
				}

			}
		}
	}

	private void realizarAtendimento() {
		agendamento.setStatus(Constantes.STATUS_EM_ATENDIMENTO);
		new ControladorAgendamento().atualizar(agendamento);
		TelaPrincipal.alteraPanel(new TelaConsulta(agendamento));
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String comando = e.getActionCommand();

		if (comando.equals(btnRealizarAtendimento.getActionCommand())) {
			realizarAtendimento();
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		int tecla = e.getKeyCode();

		if(tecla == KeyEvent.VK_DOWN || tecla == KeyEvent.VK_UP){
			int row = tableAgenda.getSelectedRow();
			acaoListenersAgenda(row);
		}

	}

	@Override
	public void keyTyped(KeyEvent e) {

	}

}
